package com.cjr.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cjr.easyexcel.dao.UploadDAO;
import com.cjr.easyexcel.entity.DownloadData;
import com.cjr.easyexcel.entity.UploadData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Scope("prototype")
public class UploadDataListener extends AnalysisEventListener<UploadData> {

    private static final int BATCH_COUNT = 3000;

    private List<UploadData> list = new ArrayList<>(BATCH_COUNT);
    @Resource
    private UploadDAO uploadDAO;
    /*public UploadDataListener(UploadDAO uploadDAO){
        this.uploadDAO=uploadDAO;
    }*/

    /**
     * 每读一行内容，都会调用一次invoke，在invoke可以操作读取到的数据
     * @param uploadData
     * @param analysisContext
     */
    @Override
    public void invoke(UploadData uploadData, AnalysisContext analysisContext) {
        list.add(uploadData);//将在Excel读到的每行数据添加到list中
        System.out.println(uploadData.toString());
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    private void saveData() {
        uploadDAO.save(list);
    }
}
